package com.bc004346.travelus.DataAccess.AsyncTasks;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;

import com.bc004346.travelus.DataAccess.TravelUsScreenScraper;
import com.bc004346.travelus.Model.Domain.Flight;
import com.bc004346.travelus.Model.Interface.ISelectFlightCallback;
import com.bc004346.travelus.Utility.Utility;

import static com.bc004346.travelus.Utility.Utility.log;

/**
 * Created by Renats on 3/12/14.
 * Search for flights
 */
public class SelectFlightTaskFragment extends Fragment {

    //<editor-fold desc="Members">
    private static final String FLIGHT = "flight";
    private ISelectFlightCallback mCallbacks;
    private TravelUsScreenScraper mTravelUS;
    private Flight mFlight;
    //</editor-fold>

    //<editor-fold desc="Static Methods">
    public static SelectFlightTaskFragment newInstance(Flight flight) {
        SelectFlightTaskFragment f = new SelectFlightTaskFragment();
        Bundle args = new Bundle();
        args.putSerializable(FLIGHT, flight);
        f.setArguments(args);
        return f;
    }
    //</editor-fold>

    //<editor-fold desc="Overrides">
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mCallbacks = (ISelectFlightCallback) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        mTravelUS = Utility.getInstance().getTravelUS();
        mFlight = (Flight) (getArguments() == null ? null : getArguments().getSerializable(FLIGHT));
        new SearchTask().execute();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }
    //</editor-fold>

    private class SearchTask extends AsyncTask<Void, Void, Void> {

        private Exception ex = null;

        @Override
        protected void onPostExecute(Void param) {
            if (mCallbacks != null) {
                mCallbacks.onSelectFlightPostExecute(mFlight, ex);
            }
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                if (mFlight.isSelected())
                    mTravelUS.selectFlight(mFlight);
                else
                    mTravelUS.unSelectFlight(mFlight);
            } catch (Exception e) {
                log(String.format("Exception: %s", e.toString()));
                ex = e;
            }
            return null;
        }
    }
}
